const express = require('express');
const multer = require('multer');
const fs = require('fs').promises;
const path = require('path');
const yaml = require('yaml');
const { spawn } = require('child_process');

const router = express.Router();

// 配置文件上传
const upload = multer({ 
  dest: 'uploads/',
  fileFilter: (req, file, cb) => {
    if (file.originalname.endsWith('.yml') || file.originalname.endsWith('.yaml')) {
      cb(null, true);
    } else {
      cb(new Error('只允许上传 YAML 文件'));
    }
  }
});

// 部署compose文件
router.post('/deploy', upload.single('composeFile'), async (req, res) => {
  try {
    if (!req.file) {
      return res.status(400).json({ error: '请上传docker-compose.yml文件' });
    }

    const filePath = req.file.path;
    const composeDir = path.dirname(filePath);
    const composeFile = path.basename(filePath);

    // 验证YAML格式
    const content = await fs.readFile(filePath, 'utf8');
    yaml.parse(content);

    // 执行docker-compose up -d
    const dockerCompose = spawn('docker-compose', ['-f', path.join(composeDir, composeFile), 'up', '-d'], {
      cwd: composeDir
    });

    let output = '';
    let error = '';

    dockerCompose.stdout.on('data', (data) => {
      output += data.toString();
    });

    dockerCompose.stderr.on('data', (data) => {
      error += data.toString();
    });

    dockerCompose.on('close', async (code) => {
      // 清理上传的文件
      await fs.unlink(filePath);

      if (code !== 0) {
        return res.status(500).json({ 
          error: '部署失败', 
          details: error || output 
        });
      }

      res.json({ 
        message: '部署成功', 
        output: output 
      });
    });

  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

module.exports = router;
